﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AssetManagementSystem.Utils;
using AssetManagementSystem.Model.IDao;

namespace AssetManagementSystem.Model {
    class HoldManager {

        IHoldDAO dao;

        public HoldManager() {
            //get the group dao
            dao = DAOManager.GetHoldDAO();
        }

        //====================================================================
        //  STANDARD CRUD METHODS
        //====================================================================

        public void CreateHold(Hold newHold) {
            dao.CreateHold(newHold);
        }

        public List<Hold> GetAllHolds() {
            return dao.GetAllHolds().ToList<Hold>();
        }

        public void DeleteHold(Hold group) {
            dao.DeleteHold(group);
        }

        //====================================================================
        //  END - STANDARD CRUD METHODS
        //====================================================================

        //====================================================================
        //  ENHANCED METHODS
        //====================================================================


        /// <summary>
        /// Attempts to find holds contain part, or all of the input text in their string representations (ToString()).
        /// The results are sorted by relevance.
        /// </summary>
        /// <param name="input">The text to search for</param>
        /// <returns>The list of sorted results</returns>
        public List<Hold> FindHolds(string input) {
            //Get all groups
            List<Hold> allHolds = GetAllHolds();
            //Create a list to store results
            List<SortObject> sortList = new List<SortObject>();
            //Get all groups with at least one tri-gram match to the input
            foreach (Hold group in allHolds) {
                int ngramMatches = SearchUtil.NGramSearch(input, group.ToString(), 3);
                if(ngramMatches > 0){
                    sortList.Add(new SortObject(ngramMatches, group));
                }
            }
            //Sort the results by the number of matches they each had
            sortList.Sort();
            //Turn the results back into a list of groups
            List<Hold> matchedHolds = new List<Hold>();
            foreach (SortObject obj in sortList) {
                matchedHolds.Add((Hold)obj.TheObject);
            }
            //return the sorted results
            return matchedHolds;
        }

        //====================================================================
        //  END - ENHANCED METHODS
        //====================================================================
    }
}
